package com.yao.code;

import com.yao.tool.ListNode;

/**
 * @author yaoquanwei
 * @date 2021/8/18 22:48
 */
public class Code210818 {
    /**
     * 剑指offer 18.删除链表的节点
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        if (head.val == val) {
            return head.next;
        }
        ListNode nodePre = head;
        ListNode nodeCurr = nodePre.next;
        while (nodeCurr != null) {
            if (nodeCurr.val == val) {
                nodeCurr = nodeCurr.next;
                nodePre.next = nodeCurr;
                break;
            } else {
                nodePre = nodeCurr;
                nodeCurr = nodeCurr.next;
            }
        }
        return head;
    }

    /**
     * 剑指offer 22.链表中的倒数第K个节点
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode frontNode = head, behindNode = head;
        while (frontNode != null && k > 0) {

            frontNode = frontNode.next;
            k--;
        }

        while (frontNode != null) {

            frontNode = frontNode.next;
            behindNode = behindNode.next;
        }

        return behindNode;
    }
}
